package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.FileUtils;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import longrise.phone.com.bjjt_henan.Adapter.AccidentLoadPicAdapter;
import longrise.phone.com.bjjt_henan.Constant.MsgConstant;
import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.UiUtils;

/**
 * 上传事故照片界面，Created by Administrator on 2016/5/12.
 */
public class NewAccidentLoadPicView extends LFView implements View.OnClickListener, ILSMsgListener,
        MainActivity.OnActivityReturnBitmap, AdapterView.OnItemClickListener {

    public static int DSIZE = 6;//默认总数目

    public static int ASIZE = 3;//补拍总数目

    private Context context;
    private View view;
    private GridView mGridView;
    private Button mBtn;
    private String caseNo;
    private BaseApplication mApplication;
    private EntityBean[] unqualifylist;//审核失败的图片集合
    private EntityBean[] isqualifylist;//审核通过的图片集合
    private int fromWhere;//0是正常的跳转，1是照片审核后跳转来的,审核后过来的，要将已经上传成功的照片展示出来
    private List<EntityBean> picLists;//显示的图片集合
    private AccidentLoadPicAdapter picAdapter;
    private EntityBean curBean;//当前点击的选项
    private boolean isSuccess = false;//上传是否成功
    private List<Runnable> loadPics;//上传图片的队列
    private int curSize = 0;// 当前已上传的总数目
    private Dialog processDialog;
    private String isSingle;

    public NewAccidentLoadPicView(Context c, String caseNo, int fromWhere) {
        super(c);
        this.context = c;
        this.caseNo = caseNo;
        this.mApplication = (BaseApplication) c.getApplicationContext();
        this.fromWhere = fromWhere;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    public void setUnqualifylist(EntityBean[] unqualifylist) {
        this.unqualifylist = unqualifylist;
    }

    public void setIsqualifylist(EntityBean[] isqualifylist) {
        this.isqualifylist = isqualifylist;
    }

    //设置事故时单车还是双车类型
    public void setCaseType(String isSingle) {
        this.isSingle = isSingle;
        if (TextUtils.equals(isSingle, "0")) {//单车
            DSIZE = 3;
        } else if (TextUtils.equals(isSingle, "1")) {//双车
            DSIZE = 6;
        }
    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        setShowtitle(false);
        initViews();
        initValues();
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (view == null) {
                return;
            }
            UiUtils.changeText("(" + curSize + "/" + loadPics.size() + ")" + "");
            if (msg.what != loadPics.size()) {
                if (curSize == 1) {// 第一张上传成功
                    for (int i = 1; i < loadPics.size(); i++) {
                        myHandler.post(loadPics.get(i));
                    }
                }
            } else {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {
                        processDialog.dismiss();
                    }
                }
                isSuccess = true;
                curSize = 0;//初始化i
                showNext();
            }
        }
    };

    //弹出照片上传正常的dialog
    private void showNext() {
        String title = "事故照片上传成功，请进入下一步。";
        UiUtils.showDialog(context, null, null, title, "返回", "确认",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        return;
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //进入事故审核页面
                        AccidentCheckView accidentcheckview = new AccidentCheckView(context, caseNo, 0);
                        FrameworkManager.getInstance().showNewForm(context, accidentcheckview);
                        isSuccess = false;
                    }
                });
    }

    //初始化事故布局及注册事件
    public void initViews() {
        if (context == null) {
            return;
        }
        view = LayoutInflater.from(context).inflate(R.layout.view_newaccident_loadpic, null);
        if (view == null) {
            return;
        }
        //标题栏
        TextView titleTV = (TextView) view.findViewById(R.id.tv_title);
        titleTV.setText("上传事故照片");
        view.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeForm();
                OnDestroy();
            }
        });
        mBtn = (Button) view.findViewById(R.id.btn_dcqz);
        mGridView = (GridView) view.findViewById(R.id.newaccident_loadpic_gridview);
        picAdapter = new AccidentLoadPicAdapter(context);
        picAdapter.setIsSingle(isSingle);
        mGridView.setAdapter(picAdapter);

        regEvent(true);
    }

    private void initValues() {
        if (picLists == null) {
            picLists = new ArrayList<EntityBean>();
        } else {
            picLists.clear();
        }
        if (fromWhere == 1) {//审核失败重拍
            if (null != isqualifylist) {//通过的图片
                for (int i = 0; i < isqualifylist.length; i++) {
                    EntityBean bean = new EntityBean();
                    String imagetype = (String) isqualifylist[i].get("imagetype");
                    String imageurl = (String) isqualifylist[i].get("imageurl");
                    bean.set("type", imagetype);
                    bean.set("url", imageurl);
                    picLists.add(bean);
                    bean = null;
                }
            }
            if (null != unqualifylist) {//不通过的图片
                for (int i = 0; i < unqualifylist.length; i++) {
                    EntityBean bean = new EntityBean();
                    int imagetype = (int) unqualifylist[i].get("imagetype");
                    bean.set("type", imagetype);
                    picLists.add(bean);
                    bean = null;
                }
            }
            //按照图片类型排序
            Collections.sort(picLists, new Comparator<EntityBean>() {
                @Override
                public int compare(EntityBean lhs, EntityBean rhs) {
                    Integer lType = Integer.valueOf(lhs.getString("type"));
                    Integer rType = Integer.valueOf(rhs.getString("type"));
                    return lType.compareTo(rType);
                }
            });
        } else if (fromWhere == 0) {//拍摄事故照片
            for (int i = 0; i < DSIZE; i++) {
                EntityBean bean = new EntityBean();
                bean.set("type", i);
                picLists.add(bean);
                bean = null;
            }
        }
        if (picLists.size() < (DSIZE + ASIZE)) {//添加默认的+号图标
            EntityBean bean = new EntityBean();
            bean.set("type", "-1");
            picLists.add(bean);
            bean = null;
        }
        picAdapter.setLists(picLists);
        picAdapter.notifyDataSetChanged();
    }

    private void regEvent(boolean b) {
        if (mBtn != null) {
            mBtn.setOnClickListener(b ? this : null);
        }
        if (null != mGridView) {
            mGridView.setOnItemClickListener(b ? this : null);
        }
        if (b) {
            this.addILSMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
        }
    }


    @Override
    public void refresh() {

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_dcqz:
                if (isSuccess) {
                    showNext();
                    return;
                }
                if (!checkTakePhoto()) {
                    UiUtil.showToast(getContext(), "请您拍摄完照片后进行下一步");
                    return;
                }
                //上传照片
                processDialog = UiUtils.showProcessDialogPro(getContext(), "正在上传");
                uploadImgInfo();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        curBean = picLists.get(position);
        String url = curBean.getString("url");
        if (!TextUtils.isEmpty(url)) {
            UiUtil.showToast(context, "本张照片已经审核通过，不需要重新拍摄！");
            return;
        }
        String type = curBean.getString("type");
        if (TextUtils.equals(type, "-1")) {//点击的+号图标
            if (picLists.size() > (DSIZE + ASIZE)) {
                UiUtil.showToast(context, "拍照数目已达上限！");
                return;
            }
//            curBean = new EntityBean();//补拍照片
//            curBean.set("type", "20");
//            picLists.add(picLists.size() - 1, curBean);
        }
        //启动相机拍照
//        String type = curBean.getString("type");
        switch (Integer.valueOf(type)) {
            case 0:
                getCamera("车头前方照片", "(请确保道路标线在拍摄画面中。)", R.drawable.car_6);
                break;
            case 1:
                getCamera("车尾后方照片", "(请确保道路标线在拍摄画面中。)", R.drawable.car_7);
                break;
            case 2:
                getCamera("擦碰点照片", null, R.drawable.car_5);
                break;
            case 3:
                getCamera("事故侧方照片", null, R.drawable.car_8);
                break;
            case 4:
                getCamera("对方驾驶证", null, R.mipmap.jsz_4);
                break;
            case 5:
                getCamera("对方行驶证", null, R.mipmap.xsz_5);
                break;
            default:
                getCamera("其他定责照片", null, 0);
                break;
        }
    }

    //启动相机
    public void getCamera(String title, String titleBottom, int resourceId) {
        Intent intent = new Intent(getContext(), HeNanSurfaceViewCameraActivity.class);
        Bundle bundle = new Bundle();

        if (!StringUtils.isEmpty(title)) {
            bundle.putString("title", title);
        }
        if (!StringUtils.isEmpty(titleBottom)) {
            bundle.putString("titleBottom", titleBottom);
        }

        if (resourceId != 0) {
            bundle.putInt("backGroundResourceId", resourceId);
        }
        intent.putExtras(bundle);

        if (context instanceof MainActivity) {
            ((MainActivity) context).startActivityForResult(intent, 110);
        }
    }

    /**
     * 上传图片
     */
    private void uploadImgInfo() {
        if (loadPics == null) {
            loadPics = new ArrayList<Runnable>();
        } else {
            loadPics.clear();
        }
        for (int i = 0; i < picLists.size(); i++) {
            final String path = picLists.get(i).getString("path");
            final String type = picLists.get(i).getString("type");
            if (!TextUtils.isEmpty(path)) {
                loadPics.add(new Runnable() {
                    @Override
                    public void run() {
                        useLoadingPic(getEntityBean(path, Integer.valueOf(type)));
                    }
                });
            }
        }
        //为防止后台数据库的重复插入问题，先上传一张，成功后再同时上传剩下的照片
        myHandler.post(loadPics.get(0));
    }

    /**
     * 获取图片上传需要的实体参数
     */
    private EntityBean getEntityBean(String filePath, int currentImageType) {
        EntityBean bean = new EntityBean();
        bean.set("appcaseno", caseNo);
        bean.set("imagelon", mApplication.getLongitude());
        bean.set("imagelat", mApplication.getLatitude());
        bean.set("imageaddress", mApplication.getAddress());
        // 获取图片参数
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        bean.set("imagebig", new File(filePath).length());
        bean.set("imageurl", FileUtils.File2byte(new File(filePath), false));
        bean.set("imagewide", Integer.toString(options.outWidth));
        bean.set("imageheigth", Integer.toString(options.outHeight));

        EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
        String phoneNumber = userinfo.getString("mobilephone");
        if (!StringUtils.isEmpty(phoneNumber)) {
            bean.set("casetelephoe", phoneNumber);
        }
        //拍照类型
        bean.set("shoottype", "1");//1是定责照片，2是定损照片
        bean.set("imagetype", currentImageType);
        bean.set("imagedate", CommontUtils.getNowTime());
        bean.set("areaid", mApplication.getAreaid());
        bean.set("username", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        return bean;
    }

    /**
     * 异步上传图片
     *
     * @param picBean
     */
    private void useLoadingPic(EntityBean picBean) {
        LoadDataManagerCar.getInstance(context).callService(String.valueOf(picBean.get("imagetype")),
                mApplication.getServerUrl(), URLConstant.ZDSUBMITCASEIMAGEINFOR, picBean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (result != null) {
                            EntityBean bean = (EntityBean) result;
                            if (bean != null) {
                                String restate = bean.getString("restate");
                                if ("1".equals(restate)) {
                                    curSize++;
                                    if (null != myHandler) {
                                        myHandler.sendEmptyMessage(curSize);
                                    }
                                } else {
                                    String redes = bean.getString("redes");
                                    UiUtil.showToast(context, redes);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {

                    }
                });
    }


    @Override
    public Object onLSMsg(int code, Object... arg1) {
        switch (code) {
            case MsgConstant.FINSHTAKEPHOTO:
                closeForm();
                OnDestroy();
                break;
            default:
                break;
        }
        return null;
    }

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode,
                                     Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            String path = bundle.getString("image");
            if (path == null) {
                UiUtil.showToast(context, "照片拍摄失败！");
                return;
            }
            if (null == curBean) {
                return;
            }
            String type = curBean.getString("type");
            if (TextUtils.equals(type, "-1")) {
                curBean = new EntityBean();//补拍照片
                curBean.set("type", "20");
                picLists.add(picLists.size() - 1, curBean);
            }
            curBean.set("path", path);
            if (picLists.size() > (ASIZE + DSIZE)) {
                //拍照数目已达上限则移除+号项
                picLists.remove(picLists.size() - 1);
            }
            picAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 验证图片是否拍摄
     *
     * @return
     */
    private boolean checkTakePhoto() {
        int size = picLists.size();
        if (size < (DSIZE + 1)) {
            return false;
        }
        for (int i = 0; i < size; i++) {
            EntityBean bean = picLists.get(i);
            String type = bean.getString("type");
            if (!TextUtils.equals(type, "-1")) {
                String url = bean.getString("url");
                String path = bean.getString("path");
                if (TextUtils.isEmpty(url) && TextUtils.isEmpty(path)) {//照片未拍摄
                    return false;
                }
            }
        }
        return true;
    }


    @Override
    public void OnDestroy() {
        super.OnDestroy();
        regEvent(false);
        if (null != unqualifylist) {
            unqualifylist = null;
        }
        if (null != isqualifylist) {
            isqualifylist = null;
        }
        if (null != picLists) {
            picLists.clear();
            picLists = null;
        }
        if (null != loadPics) {
            if (null != myHandler) {
                for (Runnable runnable : loadPics)
                    myHandler.removeCallbacks(runnable);
            }
            loadPics.clear();
            loadPics = null;
        }
        if (null != processDialog) {
            processDialog.dismiss();
            processDialog = null;
        }
        picAdapter = null;
        if (mGridView != null) {
            mGridView.setAdapter(null);
            mGridView = null;
        }
        myHandler = null;
        view = null;
    }
}